package updater.gui;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Map;

import xml.ReadXMLFile;
import xml.WriteXMLFile;

public class Preferences {

	public static final String fileName = "preferences.xml";
	public static final String rootName = "preferences";
	public static final String VERSION_CODE_TAG = "version_code";
	public static final String APPLICATION_FOLDER_TAG = "application_folder";
	public static final String APPLICATION_LAUNCHER_TAG = "main_application";
	public static final String UPDATE_URL_TAG = "update_url";

	public static final String[] keys = { VERSION_CODE_TAG, APPLICATION_FOLDER_TAG, APPLICATION_LAUNCHER_TAG, UPDATE_URL_TAG };

	private Map<String, String> values = new HashMap<String, String>();

	public Preferences() {
		readPreferences();
	}

	private void readPreferences() {
		try {
			values = new ReadXMLFile().parse(new FileInputStream(new File(fileName)), keys);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			values = new HashMap<String, String>();
			for (String key : keys) {
				values.put(key, "");
			}
		}

		for (String key : values.keySet()) {
			System.out.println(key + " " + values.get(key));
		}
	}

	public String getValue(String key) {
		return values.get(key);
	}

	public String getVersionCode() {
		return values.get(VERSION_CODE_TAG);
	}

	public String getApplicationFolder() {
		return values.get(APPLICATION_FOLDER_TAG);
	}

	public String getMainApplication() {
		return values.get(APPLICATION_LAUNCHER_TAG);
	}

	public String getUpdateUrl() {
		return values.get(UPDATE_URL_TAG);
	}

	public void setVersionCode(String code) {
		values.put(VERSION_CODE_TAG, code);
		savePreferences();
	}

	public void setApplicationFolder(String applicationFolder) {
		values.put(APPLICATION_FOLDER_TAG, applicationFolder);
		savePreferences();
	}

	public void setMainApplication(String applicationLauncher) {
		values.put(APPLICATION_LAUNCHER_TAG, applicationLauncher);
		savePreferences();
	}

	public void setUpdateUrl(String newUpdateUrl) {
		values.put(UPDATE_URL_TAG, newUpdateUrl);
		savePreferences();
	}

	private void savePreferences() {
		new WriteXMLFile().saveToXML(fileName, rootName, values);
	}

	public static void main(String[] args) {
		Preferences pref = new Preferences();
		pref.setVersionCode("1115");
		pref.savePreferences();
	}

}
